package com.heima.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    private final int MAX_SIZE = 50;



    @Override
    public ResponseResult loadArticle(Short loadType, ArticleHomeDto articleHomeDto) {
        //每页展示条数的校验参数：如果前端没有传递，默认是10。限制大小最大加载50条。
        Integer size = articleHomeDto.getSize();
        if(size==null || size ==0){
            size = 10;
        }
        size = Math.min(size,MAX_SIZE);
        articleHomeDto.setSize(size);
        //加载类型【上拉或者下拉】类型参数检验：如果前端没有传递，默认是上拉【加载更多】
        if(!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadType)
                && !ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadType)){
            loadType = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验：如果前端没有传递，默认是加载所有 __all__
        String tag = articleHomeDto.getTag();
        if(StringUtils.isEmpty(tag)){
            articleHomeDto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间校验：如果前端没有传递时间，使用当前系统时间
        if(articleHomeDto.getMaxBehotTime()==null){
            articleHomeDto.setMaxBehotTime(new Date());
        }
        if(articleHomeDto.getMinBehotTime()==null){
            articleHomeDto.setMinBehotTime(new Date());
        }
        List<ApArticle> apArticles = apArticleMapper.loadArticle(loadType, articleHomeDto);
        return ResponseResult.okResult(apArticles);
    }
}
